<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input placeholder="金额">
    <script>
        const emptyObj = (obj) => {
            let value = JSON.stringify(obj)
            return value == '{}' || value == '[]';
        }

        const isExist = (value, zeroValid = false) => {
            let flag = true;
            // 空字符串认为不存在
            /^\s*$/.test(value) && (flag = false)
            // 如果是一个数，并且0是有效值，认为是不存在的
            if (/^-*\d+(\.\d+)?$/.test(value)) {
                if ((value == 0 && !zeroValid) || value < 0) {
                    flag = false;
                }
            } else {
                flag && (flag = !!value);
            }
            //空对象
            emptyObj(value) && (flag = false);
            //空数组
            Array.isArray(value) && value.length == 0 && (flag = false);
            return flag;
        };

        const input = document.getElementsByTagName('input')[0]
        let lock = false;
        input.addEventListener('compositionstart', () => {
            lock = true;
        })
        input.addEventListener('compositionend', () => {
            lock = false;
            input.dispatchEvent(new Event('input'))
        })
        input.addEventListener('input', (e) => {
            if (lock) { return }
            let value = e.target.value;
            let selectionStart = e.target.selectionStart;
            const reg = new RegExp("(?:[^-.0-9]+)?\\-*(0*)([1-9]\\d*)?(\\.(?:\\d{1,2})?)?(?:[^-.0-9]+)?", "g");
            const matches = reg.exec(value);
            let $1 = ''
            if (isExist(matches[1], true)) {
                matches[1].length > 1 && selectionStart--;
                $1 = matches[1].replace(/0+/, '0');
            }
            const $2 = matches[2] || '';
            const $3 = matches[3] || '';
            if ($1 == '0') {
                if ($2) {
                    value = $2 + $3;
                } else {
                    value = $1 + $3;
                }
            } else {
                value = $2 + $3
            }
            e.target.value = value;
            e.target.setSelectionRange(selectionStart, selectionStart)
        })

        input.addEventListener('blur', (e) => {
            let value = e.target.value;
            e.target.value = Number(value).toFixed(2)
        })

    </script>
</body>

</html>